//
//  LoginViewController.m
//  SimpleTable
//
//  Created by seaway on 13-4-17.
//  Copyright (c) 2013年 seaway. All rights reserved.
//

#import "LoginViewController.h"
#import "SVProgressHUD.h"
#import <QuartzCore/QuartzCore.h>
//#import "ViewController.h"
#import "AppDelegate.h"
//#import "SettingViewController.h"
//#import "contactsEntity.h"
#import "UserEntity.h"
#import "RegisterViewController.h"
//#import "ForgetPasswordVC.h"
#import "RDVTabBarController.h"
#import "Glob.h"
@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize nameField = _nameField, pwdField = _pwdField,backView = _backView,loginhead=_loginhead, loginButton = _loginButton,registerButton = _registerButton,nameLabel = _nameLabel, pwdLabel = _pwdLabel, loginView = _loginView,forgetpwdBtn=_forgetpwdBtn,forgetpwdImg=_forgetpwdImg,forgetpwdLab=_forgetpwdLab,autoLoginBtn=_autoLoginBtn,autoLoginLab=_autoLoginLab;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"登录";
    }
    return self;
}
-(void)back:(id)sender
{
    if (self.IsHideTabBar == 1) {
        [Glob showTabBar];
    }
    //    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [Glob hideTabBar];
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    //retrieve the data
    if (username == nil) {
        _nameField.text = @"";
    }
    else
    {
        _nameField.text = username;
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    //    if (self.IsHideTabBar == 1) {
    //        [Glob showTabBar];
    //    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //    if (self.type == oneTimeLogin) {
    self.navigationItem.leftBarButtonItem = [Glob getNavigationBarBackButton:self imgName:@"fanhuianniu.png"];
    //    }
    //    else
    //        self.navigationItem.leftBarButtonItem = nil;
    self.delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    CGRect rect = [[UIScreen mainScreen] bounds];
    _loginView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
    [self.view addSubview:_loginView];
    _loginhead=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, 170)];
    [_loginhead setImage:[UIImage imageNamed:@"login_top.png"]];
    [_loginView addSubview:_loginhead];
    
    self.view.backgroundColor = mRGBColor(230, 229, 227);
    
    //背景
    _backView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 210 , 284, 86)];
    [_backView setImage:[UIImage imageNamed:@"zhuce_kuang.png"]];
    [self.loginView addSubview:_backView];
    
    //用户名
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 215 , 70, 35)];
    _nameLabel.backgroundColor = [UIColor clearColor];
    _nameLabel.textColor = [UIColor blackColor];
    _nameLabel.text = @"用 户 名:";
    
    _nameField = [[UITextField alloc] initWithFrame:CGRectMake(100, 215 , 200, 35)];
    _nameField.delegate = self;
    _nameField.tag = 10001;
    //    _nameField.placeholder = @"用户名/手机号/速度速度速度速度是的是的";
    _nameField.returnKeyType = UIReturnKeyNext;
    _nameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [_nameField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.loginView addSubview:_nameLabel];
    [self.loginView addSubview:_nameField];
    
    //密码
    _pwdLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 258 , 70, 35)];
    _pwdLabel.backgroundColor = [UIColor clearColor];
    _pwdLabel.textColor = [UIColor blackColor];
    _pwdLabel.text = @"密      码:";
    
    _pwdField = [[UITextField alloc] initWithFrame:CGRectMake(100, 258 , 200, 35)];
    _pwdField.delegate = self;
    _pwdField.tag = 10002;
    //    _pwdField.placeholder = @"请输入密码速度速度速度撒速度速度";
    _pwdField.returnKeyType = UIReturnKeyDone;
    _pwdField.secureTextEntry = YES;
    _pwdField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [_pwdField addTarget:self action:@selector(accessCodeTextFiledDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.loginView addSubview:_pwdLabel];
    [self.loginView addSubview:_pwdField];
    
    //登录按钮
    _loginButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 340 + 30 -10, 130, 39)];
    UIImage *nImage1 = [[UIImage imageNamed:@"login_button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    [_loginButton setBackgroundImage:nImage1  forState:UIControlStateNormal];
    //    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_loginButton addTarget:self action:@selector(doLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView addSubview:_loginButton];
    
    //注册按钮
    _registerButton = [[UIButton alloc] initWithFrame:CGRectMake(_loginButton.right + 25, 340 + 30 -10, 130, 39)];
    UIImage *nImage2 = [[UIImage imageNamed:@"zhuceanniu.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    [_registerButton setBackgroundImage:nImage2  forState:UIControlStateNormal];
    //    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_registerButton addTarget:self action:@selector(doRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView addSubview:_registerButton];
    
    //忘记密码
    _forgetpwdImg=[[UIView alloc]initWithFrame:CGRectMake(210, 20+45+45+50 - 10, 60, 1)];
    _forgetpwdImg.backgroundColor = [UIColor colorWithRed:195/255.0 green:194/255.0 blue:194/255.0 alpha:1.0];
    _forgetpwdLab=[[UILabel alloc]initWithFrame:CGRectMake(200+10, 200+45+45+37.5 -2 - 10, 60, 15)];
    _forgetpwdLab.font=[UIFont systemFontOfSize:15];
    _forgetpwdLab.textColor=[UIColor colorWithRed:195/255.0 green:194/255.0 blue:194/255.0 alpha:1.0];
    _forgetpwdLab.text=@"忘记密码";
    
    _forgetpwdLab.backgroundColor=[UIColor clearColor];
    _forgetpwdBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    _forgetpwdBtn.frame=CGRectMake(190, 200+45 *2+40 -2 - 20, 100, 35);
    _forgetpwdBtn.backgroundColor=[UIColor clearColor];
    [_forgetpwdBtn addTarget:self action:@selector(forgetPwdAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _autoLoginLab=[[UILabel alloc]initWithFrame:CGRectMake(50, 200+45+45+37.5 -12 , 60, 15)];
    _autoLoginLab.font=[UIFont systemFontOfSize:15];
    _autoLoginLab.text=@"自动登录";
    
    _autoLoginLab.backgroundColor=[UIColor clearColor];
    _autoLoginBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    _autoLoginBtn.frame=CGRectMake(35, 200+45*2+40 - 20 -2 , 100, 35);
    _autoLoginBtn.backgroundColor=[UIColor clearColor];
    [_autoLoginBtn addTarget:self action:@selector(autologin:) forControlEvents:UIControlEventTouchUpInside];
    
    defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:@"yes" forKey:@"isAutoLogin"];
    isAutoLogin=YES;
    if ([defaults objectForKey:@"remUserName"]) {
        _nameField.text=[defaults objectForKey:@"remUserName"];
    }else{
        _nameField.text=@"";
    }
    YesOrNoAuto=[defaults objectForKey:@"isAutoLogin"];
    if (YesOrNoAuto) {
        if ([YesOrNoAuto isEqualToString:@"no"]) {
            _autoLoginLab.textColor=[UIColor colorWithRed:195/255.0 green:194/255.0 blue:194/255.0 alpha:1.0];
            isAutoLogin=NO;
        }else if ([YesOrNoAuto isEqualToString:@"yes"]){
            _autoLoginLab.textColor=[UIColor colorWithRed:255/255.0 green:154/255.0 blue:12/255.0 alpha:1.0];
            isAutoLogin=YES;
        }
    }else{
        _autoLoginLab.textColor=[UIColor colorWithRed:195/255.0 green:194/255.0 blue:194/255.0 alpha:1.0];
        isAutoLogin=NO;
    }
    [self.loginView addSubview:_forgetpwdImg];
    [self.loginView addSubview:_forgetpwdLab];
    [self.loginView addSubview:_forgetpwdBtn];
    [self.loginView addSubview:_autoLoginLab];
    [self.loginView addSubview:_autoLoginBtn];
    
}

-(void)forgetPwdAction:(UIButton *)sender{
    [SVProgressHUD showWithStatus:@"该功能还在开发中" maskType:SVProgressHUDMaskTypeClear];
    [self performSelector:@selector(dismiss:) withObject:nil afterDelay:1.5f];
    //    ForgetPasswordVC *vc = [[ForgetPasswordVC alloc] initWithNibName:nil bundle:nil];
    //    [vc setHidesBottomBarWhenPushed:YES];
    //    [self.navigationController pushViewController:vc animated:YES];
}

-(void)autologin:(UIButton *)sender{
    
    if (isAutoLogin) {
        NSLog(@"不自动登录");
        _autoLoginLab.textColor=[UIColor colorWithRed:195/255.0 green:194/255.0 blue:194/255.0 alpha:1.0];
        [defaults setObject:@"no" forKey:@"isAutoLogin"];
        isAutoLogin=NO;
    }else{
        NSLog(@"自动登录");
        _autoLoginLab.textColor=[UIColor colorWithRed:255/255.0 green:154/255.0 blue:12/255.0 alpha:1.0];
        [defaults setObject:@"yes" forKey:@"isAutoLogin"];
        isAutoLogin=YES;
    }
}

-(void)getcompanyBack
{
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_nameField becomeFirstResponder];
}
-(void)accessCodeTextFiledDone:(id)sender
{
    [self doLogin];
}

-(void)accessCodeTextFiledNext:(id)sender
{
    UITextField *field = sender;
    if (field.tag == 10001) {
        [_pwdField becomeFirstResponder];
    }
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //    if (textField.tag == 10001){
    //        [self.view endEditing:YES];
    
    //        [self showMore];
    //        return NO;
    //    }
    
    return YES;
}



#pragma mark 显示审批流程 选项
-(void)showMore
{
    //    [self getcompanyBack];
}

//普通用户登录
- (void)doLogin
{
    NSString *user = self.nameField.text;
    NSString *pwd = self.pwdField.text;
    NSString *message = [[NSString alloc] init];
    if (user == nil || [user isEqualToString:@""])
    {
        message = @"用户名不能为空";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        self.loginButton.userInteractionEnabled = YES;
    }
    else if (pwd == nil || [pwd isEqualToString:@""])
    {
        message = @"密码不能为空";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        self.loginButton.userInteractionEnabled = YES;
        
    }
    else
    {
        [SVProgressHUD showWithStatus:@"登录中..." maskType:SVProgressHUDMaskTypeClear];
        self.loginButton.userInteractionEnabled = YES;
        //活动详细 传参
        NSMutableArray *params1=[NSMutableArray array];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:user,@"username", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:pwd,@"password", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:DEFAULT_CODE,@"code", nil]];
//        ASIServiceArgs *args2=[[ASIServiceArgs alloc] init];
//        args2.methodName=@"Login";
//        args2.soapParams=params1;
//        
//        NSLog(@"soap=%@\n",args2.bodyMessage);
//        
//        ASIServiceHTTPRequest *request=[ASIServiceHTTPRequest requestWithArgs:args2];
//        [request success:^{
//            NSLog(@"请求头=%@",request.ServiceArgs.headers);
//            NSLog(@"请求body=%@",request.ServiceArgs.bodyMessage);
//            if (request.ServiceResult.success) {
//                id json=[request.ServiceResult json];
//                NSLog(@"登录请求结果：%@",json);
//                if ([json isKindOfClass:[NSDictionary class]]) {
//                    NSDictionary *dic=json;
//                    if (![dic objectForKey:@"userid"]) {
//                        [self performSelector:@selector(dismiss:) withObject:nil afterDelay:1.5];
//                        [SVProgressHUD showSuccessWithStatus:@"用户名或密码错误"];
//                        [self performSelector:@selector(dismiss:) withObject:nil afterDelay:1.5];
//                    }
//                    else
//                    {
//                        [[NSUserDefaults standardUserDefaults] setObject:user forKey:@"username"];
//                        NSUserDefaults *accountList = [NSUserDefaults standardUserDefaults];
//                        //retrieve the data
//                        if ([accountList objectForKey:@"account"] == nil) {
//                            [accountList setObject:[NSArray array] forKey:@"account"];
//                        }
//                        NSMutableArray *accountArray = [[accountList objectForKey:@"account"] mutableCopy];
//                        NSLog(@"user name is %@ %@",user,pwd);
//                        NSDictionary *userdic = @{@"username": user,@"password":pwd};
//                        [accountArray addObject:userdic];
//                        [accountList setObject:accountArray forKey:@"account"];
//                        [accountList synchronize];
//                        UserEntity* entity = [Glob getUserInfo];
//                        //                        entity = [UserEntity createWithDictionary:dic andPassword:pwd];
//                        if (entity) {
//                            entity.uid = [dic objectForKey:@"userid"];
//                            entity.encryptkeys = [dic objectForKey:@"encryptkeys"];
//                            entity.name = [dic objectForKey:@"username"];
//                            entity.usertype = [dic objectForKey:@"usertype"];
//                            entity.phone = [dic objectForKey:@"phone"];
//                            entity.password = pwd;
//                            entity.zname=[dic objectForKey:@"nickname"];
//                            entity.pic=[NSString stringWithFormat:@"%@%@",IMAGEPATH,[dic objectForKey:@"pic"]];
//                            entity.email=[dic objectForKey:@"email"];
//                            entity.signature=[dic objectForKey:@"signature"];
//                            entity.integral = [dic objectForKey:@"integral"];
//                            if ([entity.integral isEqualToString:@""]) {
//                                entity.integral = @"0";
//                            }
//                            entity.level = [dic objectForKey:@"level"];
//                            if ([entity.level isEqualToString:@""]) {
//                                entity.level = @"1";
//                            }
//                            entity.beans = [dic objectForKey:@"beans"];
//                            if ([entity.beans isEqualToString:@""]) {
//                                entity.beans = @"0";
//                            }
//                            
//                        }
//                        else{
//                            entity = [UserEntity createWithDictionary:dic andPassword:pwd];
//                        }
//                        
//                        [entity saveUserAccount];
//                        [Glob setUserInfo:entity];
//                        NSLog(@"活动详细 解析xml结果=%@\n",dic);
//                        [UserInfo sharedUser].isLogin = YES;
//                        [SVProgressHUD dismiss];
//                        [SVProgressHUD showSuccessWithStatus:@"登录成功"];
//                        [self performSelector:@selector(dismiss:) withObject:nil afterDelay:1];
//                        //                        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOGIN_PUSH_BACK_NOTIFICATION" object:nil];
//                        [self back:nil];
//                    }
//                    
//                }
//                
//            }
//            else
//            {
//            }
//        } failure:^{
//            NSLog(@"error=%@\n",request.error.description);
//            [SVProgressHUD dismiss];
//            [SVProgressHUD showSuccessWithStatus:@"登录失败"];
//            [self performSelector:@selector(dismiss:) withObject:nil afterDelay:1];
//        }];
//        if ([[defaults objectForKey:@"saveUser"] isEqualToString:@"yes"]) {
//            [defaults setObject:_nameField.text forKey:@"remUserName"];
//        }
    }
}

- (void)dismiss:(id)sender {
    [SVProgressHUD dismiss];
}

//跳转到注册页面
- (void)doRegister
{
    RegisterViewController *registerCon = [[RegisterViewController alloc] initWithNibName:nil bundle:nil];
    [registerCon setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:registerCon animated:YES];
}

- (void)postedMessage:(NSString*)message
{
    [SVProgressHUD showWithStatus:message];
    [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:.6f];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidUnload
{
    [super viewDidUnload];
}

-(BOOL)checkString:(NSString*)string1 InString:(NSString*)string2
{
    NSRange range=[string2 rangeOfString:string1];
    if(range.location!=NSNotFound){
        return true;
    }else{
        return false;
    }
}
@end
